package com.lyb.spzx.manager.service.impl;

import com.lyb.spzx.common.exception.DefinedException;
import com.lyb.common.utils.AuthContextUtil;
import com.lyb.spzx.manager.helper.MenuHelper;
import com.lyb.spzx.manager.mapper.SysMenuMapper;
import com.lyb.spzx.manager.service.SysMenuService;
import com.lyb.spzx.model.dto.system.system.SysMenu;
import com.lyb.spzx.model.dto.system.system.SysUser;
import com.lyb.spzx.model.vo.common.ResultCodeEnum;
import com.lyb.spzx.model.vo.system.SysMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;

@Service
@Transactional
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> findNodes() {
       List<SysMenu> sysMenus =  sysMenuMapper.findAllMenu();
       if (CollectionUtils.isEmpty(sysMenus)){
           throw new DefinedException(ResultCodeEnum.DATA_ERROR);
       }
        return MenuHelper.buildTrees(sysMenus);
    }

    @Override
    public void saveMenu(SysMenu sysMenu) {
        sysMenuMapper.save(sysMenu);
    }

    @Override
    public void updateMenu(SysMenu sysMenu) {
        sysMenuMapper.update(sysMenu);
    }

    @Override
    public void deleteMenu(Long id) {
        //先查询是否有子菜单，有，不能删除
        int count = sysMenuMapper.countByParentId(id);
        if (count > 0){
            throw new DefinedException(ResultCodeEnum.NODE_ERROR);
        }
        sysMenuMapper.delete(id);
    }

    @Override
    public List<SysMenuVo> findUserMenuList() {
        //获取当前登录用户的id
        SysUser sysUser = AuthContextUtil.get();
        Long userId = sysUser.getId();
        //调去DAO层
        List<SysMenu> sysMenuList = sysMenuMapper.findMenuById(userId);
        //构建树形结构
        List<SysMenu> sysMenus = MenuHelper.buildTrees(sysMenuList);
        //将SysMenu对象转换成SysMenuVo对象
        List<SysMenuVo> sysMenuVos = buildMenus(sysMenus);
        return sysMenuVos;
    }

    private List<SysMenuVo> buildMenus(List<SysMenu> sysMenus) {
        List<SysMenuVo> sysMenuVos = new LinkedList<>();
        for (SysMenu sysMenu : sysMenus) {
            SysMenuVo menuVo = new SysMenuVo();
            menuVo.setTitle(sysMenu.getTitle());
            menuVo.setName(sysMenu.getComponent());
            List<SysMenu> children = sysMenu.getChildren();
            if (!CollectionUtils.isEmpty(children)){
                menuVo.setChildren(buildMenus(children));
            }
            sysMenuVos.add(menuVo);
        }
        return sysMenuVos;
    }
}
